define(['../../common/common', '../../common/pathCompute', 'ztree', 'text!../../../pages/project/project.html', 'text!../../../pages/project/projectTreeAdd.html'], function($, pathfn, ztree, projectHtml, projectTreeAddHtml) {
	var interface = pathfn.interface,
		tableHeight = $(window).height() - $('#budget-header').height() - $('.layui-footer').height() - 80;
	var projectJs = function() {
		$('.page-content').html(projectHtml);
		layui.use(['table', 'form', 'laypage'], function() {
			var table = layui.table,
				form = layui.form,
				element = layui.element,
				laypage = layui.laypage;
				init = function() {
					bindEvents();
					ztreeOperate.ztreeInit();
					tableOperate.tableOneInit(0, 0);
				},
				ztreeOperate = {
					setting: {
						view: {
							showIcon: true,
							selectedMulti: false,
							dblClickExpand: false
						},
						async: {
							enable: true,
							url: interface.projectTree,
							autoParam: ["node=='root'"],
							otherParam: {
								"source": "init"
							}
						},
						data: {
							key: {
								title: "",
								name: 'text'
							}
						},
						callback: {
							onAsyncSuccess: function(event, treeId, treeNode, msg) {
								console.log(treeId, treeNode)
								var treeObj = $.fn.zTree.getZTreeObj("tree-list4"),
									//获取ztree 所有节点
									getNodes = treeObj.getNodes();
								//获取ztree 第一个节点
								treeObj.selectNode(getNodes[0]);
								//給第一个节点触发点击事件，显示右边table
								ztreeOperate.setting.callback.onClick('click', 'tree-list4', getNodes);
								//展开ztree
								treeObj.expandAll(true);
								$('.content-loading').remove();
							},
							onClick: function(even, treeId, treeNode) {
								var treeNode = treeNode[0] || treeNode;
								if (treeNode.level == 0 || treeNode.level == 1) {
									if (tableOperate.displayTable == 0) {
										tableOperate.tableReload({
											pro: (treeNode.level + 1),
											projectId: treeNode.id
												// ,
												// start:0
										});
									} else {
										tableOperate.tableOneInit(treeNode.id, treeNode.level);
									}
								} else if (treeNode.level == 2) {
									if (tableOperate.displayTable == 1) {
										tableOperate.tableReload({
											bitProjectId: treeNode.id
												// ,
												// start:0
										});
									} else {
										tableOperate.tableTwoInit(treeNode.id, treeNode.level);
									}
								}
							},
							onDblClick: function(event, treeId, treeNode) {
								ztreeOperate.zTreeOpen(treeId, treeNode);
							}
						}
					},
					ztreeInit: function() { //加载左侧菜单树
						$.fn.zTree.init($("#tree-list4"), this.setting);
					},
					zTreeAdd: function(isParent) {
						var _this = this;
						var zTree = $.fn.zTree.getZTreeObj("tree-list4"),
							nodes = zTree.getSelectedNodes();
						// console.log(zTree.getNodes())
						if ((isParent == true) && ((nodes.length == 0) || ((nodes.length == 1) && (nodes[0].level != 0)))) {
							layer.msg('请选择项目');
							return;
						}
						if ((isParent == false) && ((nodes.length == 0) || ((nodes.length == 1) && (nodes[0].level != 1)))) {
							layer.msg('请选择单项工程');
							return;
						}
						var title = isParent == true ? "新增单项工程" : "新增单位工程";
						var layeradd = layer.open({
							type: 1,
							title: title,
							content: projectTreeAddHtml,
							fixed: true,
							skin: 'lay-padding',
							scrollbar: true,
							btn: ['确定', '取消'],
							area: '400px',
							yes: function(index, layero) {
								$('.projsubmit').trigger('click');
							},
							btn2: function(index, layero) {

							},
							success: function(layero, index) {
								// _this.zTreeAddNode(isParent,nodes[0].id,layeradd);
								if (isParent == true) {
									$("input[name='parentId']").val(nodes[0].id);
									$("input[name='isLeaf']").val(1);
									$("input[name='level']").val(3);
								} else {
									$("input[name='parentId']").val(nodes[0].id);
									$("input[name='isLeaf']").val(0);
									$("input[name='level']").val(2);
								}
								form.render();
								form.on('submit(projsubmit)', function(data) {
									var formData = data.field;
									$.ajaxRequest({
										url: interface.projectTreeEdit,
										data: formData,
										successfn: function(data) {
											console.log(data)
											if (data.success == true) {
												layer.msg("添加成功");
												_this.ztreeInit();
												layer.close(layeradd);
											} else {
												layer.alert(data.msg);
											}
										},
										errorfn: function(data) {
											console.log(data);
										}
									})
									return false;
								});
							}
						});
					},
					zTreeDelete: function() {
						var _this = this,
							zTree = $.fn.zTree.getZTreeObj("tree-list4"),
							nodes = zTree.getSelectedNodes();
						if (nodes.length == 0) {
							layer.msg('请选择一项进行移除');
							return;
						}
						if (nodes.length == 1 && nodes[0].level == 0) {
							layer.msg('不能移除项目');
							return;
						}
						var layerdel = layer.open({
							type: 1,
							title: "删除",
							content: "删除该节点会同时删除已经填写的单位工程，确认删除吗?",
							fixed: true,
							scrollbar: true,
							skin: 'lay-padding',
							btn: ['是', '否'],
							area: ['300px', '180px'],
							yes: function(index, layero) {
								$.ajaxRequest({
									url: interface.projectTreeEdit,
									data: {
										"cmd": "edit",
										"projectId": nodes[0].id
									},
									successfn: function(data) {
										console.log(data)
										if (data.success == true) {
											layer.msg("删除成功");
											_this.ztreeInit();
											layer.close(layerdel);
										} else {
											layer.alert(data.msg);
										}
									},
									errorfn: function(data) {
										console.log(data);
									}
								})
							},
							btn2: function(index, layero) {},
							success: function(layero, index) {}
						});
					},
					zTreeOpen: function(treeId, treeNode){
						if(treeNode.level && treeNode.level == 2){  //单位工程
							require(['./modules/project/projectUnit', 'text!../pages/project/projectUnit.html'], function (_projectDwJs, projectPopBackHtml){
								var openObj = {
									"content": projectPopBackHtml,
									"title": '',
									"area": ['94%','94%'],
									"btn": ['',''],
									"success": function(layero, index) {
										_projectDwJs(treeNode && treeNode.id);
									}
								}
								layerOpenfn(openObj);
	　　　　				})
						}else{    //龙山雅苑
							require(['./modules/project/projectDealWith', 'text!../pages/project/projectDealWith.html'], function (_projectDwJs, projectDealWithHtml){
								var openObj = {
									"content": projectDealWithHtml,
									"title": '',
									"area": ['94%','94%'],
									"btn": ['',''],
									"success": function(layero, index) {
										_projectDwJs(treeNode && treeNode.id);
									}
								}
								layerOpenfn(openObj);
	　　　　				})
						}
						
					}
				};
			tableOperate = {
				displayTable: "",
				tableOneInit: function(id, level) {
					var _this = this,
						zTree = $.fn.zTree.getZTreeObj("tree-list4"),
						node = zTree.getSelectedNodes()[0];
					var obj = {
						id: 'project-table',
						elem: '#project-table', //指定原始表格元素选择器（推荐id选择器）
						height: tableHeight, //容器高度
						cols: [
							[ //标题栏
								{
									field: 'index',
									title: '序号',
									width: 100,
									sort: true,
									rowspan: 2
								}, {
									field: 'project_name',
									title: '名称',
									width: 100,
									sort: true,
									rowspan: 2
								}, {
									field: 'totalAmount',
									title: '项目造价(元)',
									width: 180,
									sort: true,
									rowspan: 2
								}, {
									field: 'projectPercent',
									title: '占造价百分比(%)',
									width: 80,
									sort: true,
									rowspan: 2
								}, {
									title: '其中',
									align: "center",
									colspan: 4
								}
							],
							[{
								field: 'transportFee',
								title: '运输费',
								sort: true,
								width: 100
							}, {
								field: 'materialFee',
								title: '材料费',
								sort: true,
								width: 100
							}, {
								field: 'installationFee',
								title: '安装费',
								sort: true,
								width: 100
							}, {
								field: 'csFee',
								title: '措施费',
								sort: true,
								width: 100
							}]
						],
						url: interface.projectTableParent,
						method: 'get',
						page: false,
						initSort: {
							field: 'id' //排序字段，对应 cols 设定的各字段名
								,
							type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
						},
						// limit: 20, //默认采用60
						loading: true
					};
					var _this = this,
						defaults = {
							where: {
								pro: (level + 1),
								projectId: id
							},
							done: function(res, curr, count) {
								_this.listEdit(obj, 0);
							}
						};
					$.extend(true, defaults, obj);
					table.render(defaults);
					//_this.tableEdit();              
				},
				tableTwoInit: function(id, level) {
					var obj = {
						id: 'project-table',
						elem: '#project-table', //指定原始表格元素选择器（推荐id选择器）
						height: tableHeight, //容器高度
						cols: [
							[ //标题栏
								{
									field: 'seq',
									title: '序号',
									width: 100,
									sort: true
								}, {
									field: 'feeCode',
									title: '费用代号',
									width: 180,
									sort: true
								}, {
									field: 'name',
									title: '名称',
									width: 100,
									sort: true
								}, {
									field: 'calculatedRadix',
									title: '计算基数',
									width: 80,
									sort: true
								}, {
									field: 'radixRemark',
									title: '基数说明',
									width: 80,
									sort: true
								}, {
									field: 'rate',
									title: '费率(%)',
									width: 130,
									sort: true
								}, {
									field: 'amount',
									title: '金额',
									width: 80,
									sort: true
								}, {
									field: 'remark',
									title: '备注',
									width: 80,
									sort: true
								}
							]
						],
						url: interface.projectTableChild,
						method: 'get',
						page: true, //开启分页
						initSort: {
							field: 'id' //排序字段，对应 cols 设定的各字段名
								,
							type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
						},
						limit: 10, //默认采用60
						loading: true
					};
					var _this = this,
						defaults = {
							where: {
								bitProjectId: id
							},
							done: function(res, curr, count) {
								_this.listEdit(obj, 1);
							}
						};
					$.extend(true, defaults, obj);
					table.render(defaults);
				},
				tableReload: function(where) {
					table.reload('project-table', {
						where: where
					});
				},
				listEdit: function($obj, num) {
					var _this = this,
						elem = $obj.elem,
						$caozuo = $(elem).next('.layui-table-view');
					$caozuo.find('#caozuo-box').length && $caozuo.find('#caozuo-box').remove();
					pathfn._toggleVisInit($obj.cols, $obj.elem, function() {
						form.render();
						_this.displayTable = num;
						var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
						for (var i = 0; i < inputArr.length; i++) {
							var ischecked = inputArr.eq(i).prop('checked'),
								field = $(inputArr[i]).data('field');
							if (ischecked) {
								$caozuo.find('td[data-field="' + field + '"],th[data-field="' + field + '"]').hide(0);
							} else {
								$caozuo.find('td[data-field="' + field + '"],th[data-field="' + field + '"]').show(0);
							}
						}
					});
				}

			};
			bindEvents = function() {
				$('#addDataNode').on("click", function(e) {
					e.stopPropagation();
					if ($(".addNodeList").css("display") == "none") {
						$(this).find('.addNodeList').slideDown(200);
					} else {
						$(this).find('.addNodeList').slideUp(50);
					}
				});
				$('#deleteDataNode').on("click", function(e) {
					ztreeOperate.zTreeDelete();
				});
				$('.add-node').each(function(index, el) {
					$(this).bind("click", function(event) {
						event.stopPropagation();
						var _this = this,
							isParent = eval($(_this).attr('isParent')); //判断添加章还是节
						ztreeOperate.zTreeAdd(isParent);
						$(_this).parents('.addNodeList').eq(0).slideUp(50);
					});
				});
			}
			layerOpenfn = function(openObj) {
				layer.open({
					type: openObj.type || 1,
					content: openObj.content || '',
					title: openObj.title || '',
					area: openObj.area || '450px',
					//skin: 'lay-padding',
					closeBtn: 1,
					success: function(layero, index) {
						openObj.success(layero, index) || (function() {})();
					},
					yes: function(index, layero) {
						$('.costCodeFilter').trigger('click');
					},
					btn2: function(index, layero) {}
				});
			}
			init();
		});
	}
	return projectJs;
})